#include "adui.h"

adui::adui(QObject *parent) : QObject(parent), splitter(nullptr), player(nullptr), imageLabel(nullptr)
{

}
QSplitter* adui::initUi()
{
    this->splitter = new QSplitter(Qt::Vertical);
    splitter->setGeometry(200,100,400,900);
    adDao dao;
    QStringList videos = dao.getAdResourcesPath(0);
    this->images = dao.getAdResourcesPath(1);
    QVideoWidget *videoWidget = new QVideoWidget;
    this->player = new QMediaPlayer;
    QMediaPlaylist *playlist = new QMediaPlaylist;
    for(auto path : videos)
    {
        playlist->addMedia(QMediaContent(QUrl::fromLocalFile(path)));
    }
    playlist->setPlaybackMode(QMediaPlaylist::Loop);
    player->setPlaylist(playlist);
    player->setVideoOutput(videoWidget);
    player->play();
    splitter->addWidget(videoWidget);
    connect(playlist,&QMediaPlaylist::currentIndexChanged,this,&adui::changImage);
    this->imageLabel = new QLabel;
    //this->imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // 设置尺寸策略为可扩展但高度固定
    this->changImage(0);
    splitter->addWidget(imageLabel);
    splitter->setHandleWidth(0);    // 把分屏之间的空隙去除
    // 设置上下部分所占比例
    // 整个分屏平等分为3份,第一部分占2份,第二部分占1份
    splitter->setStretchFactor(0,2);
    splitter->setStretchFactor(1,1);
    return this->splitter;
}

void adui::changePlayList()
{
    qDebug() << "修改播放列表" ;
    adDao dao;
    QStringList videos = dao.getAdResourcesPath(0);
    QMediaPlaylist *playlist = new QMediaPlaylist;
    for(auto path : videos)
    {
        playlist->addMedia(QMediaContent(QUrl::fromLocalFile(path)));
    }
    playlist->setPlaybackMode(QMediaPlaylist::Loop);
    player->setPlaylist(playlist);
    player->play();
    connect(playlist,&QMediaPlaylist::currentIndexChanged,this,&adui::changImage);
    this->images = dao.getAdResourcesPath(1);
    this->changImage(0);
}
void adui::changImage(int index)
{
    QString path = this->images.at(index);
    QPixmap map(path);
    map = map.scaled(400,300);
    //QPixmap scaledMap = map.scaled(400, 200, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    imageLabel->setPixmap(map);
}

adui::~adui()
{
    if(this->splitter != nullptr)
    {
        delete this->splitter;
    }
//    if (player)
//    {
//           player->stop();
//           player->deleteLater();
//    }
}
